package com.fingard.dsp.bank.directbank.nbcb01;


import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class NBCB01SinglePay extends NBCB01Base implements ISinglePay {

    //单笔支付，不需采用流处理方式
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail;
        tmpRetDetail = externalPayments(p_req1908);
        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    //190802对外支付
    private RetAtsSglDetail externalPayments(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        if (p_req1908.singleDetail.sameBnk.equals("1")) {//同行
            bankInnerTransfer(p_req1908, retDetail);
        } else {//跨行
            crossBankTransfer(p_req1908, retDetail);
        }
        return retDetail;
    }

    //同行支付
    private RetAtsSglDetail bankInnerTransfer(ReqSingle p_req1908, RetAtsSglDetail retDetail) throws Exception {

        serviceId = "srv006_singleInnerTransfer";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入报文头部信息
        writeCommonHeader(xmlWriter);
        if (!"".equals(bankFront.token)) {
            xmlWriter.writeElementString("functionId", "srv006");
            xmlWriter.writeElementString("functionName", "行内转账");
            xmlWriter.writeStartElement("opReq");
            xmlWriter.writeElementString("serialNo", p_req1908.singleDetail.askNumber);
            xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(new Date()));

            XElement tmpXElement = new XElement("ReqParam", "");
            tmpXElement.addChild(new XElement("FKZH", p_req1908.singleDetail.payAct));
            tmpXElement.addChild(new XElement("SKZH", p_req1908.singleDetail.recAct));
            tmpXElement.addChild(new XElement("SKHM", p_req1908.singleDetail.recName));
            tmpXElement.addChild(new XElement("JYJE", p_req1908.singleDetail.payAmount));
            tmpXElement.addChild(new XElement("BIZH", convertCurToBank(p_req1908.singleDetail.payCur)));
            tmpXElement.addChild(new XElement("YOTU", p_req1908.singleDetail.purpose));
            tmpXElement.addChild(new XElement("JTBZ", "0"));//集团业务标志 0-普通转账（默认）1-集团业务转账划拨（归集）
            nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndElement();

            String signXml = getDataSignData(xmlWriter);//获取签名数据
            if (signnatrue(signXml) == true) {
                xmlWriter.writeElementString("signData", signature);//进行签名
                xmlWriter.writeEndDocument();//报文结束
                String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));//发送给银行
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        retDetail.respCode = "0";
                        retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                        if (tmpBkReader.getFirstText("/NBCBEBankData/opRep") != null) {
                            retDetail.respInfo = tmpBkReader.getFirstText("/NBCBEBankData/opRep/opResult/SBYY");
                        ////交易应答+交易状态 0000+90  90：交易成功91：交易失败99：系统处理中
                        retDetail.transState = tmpBkReader.getFirstText("/NBCBEBankData/opRep/opResult/YDDM") + "+" + tmpBkReader.getFirstText("/NBCBEBankData/opRep/opResult/JYZT");
                        } else {
                            retDetail.respInfo = tmpBkReader.getFirstText("/NBCBEBankData/errorMsg");
                            retDetail.transState = tmpBkReader.getFirstText("/NBCBEBankData/retCode");
                        }
                        retDetail.payInfoCode = retDetail.transState;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpSbMsg.toString();
                    }
                } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                    retDetail.respCode = "0";
                    retDetail.respInfo = tmpStrRet[1];
                    retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    retDetail.transState = PaymentState.FAIL_Payment;
                    retDetail.payInfoCode = tmpStrRet[0];
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpStrRet[1];
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSign[1];
            }
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = "登录失败";
        }
        return retDetail;
    }

    //跨行支付
    private RetAtsSglDetail crossBankTransfer(ReqSingle p_req1908, RetAtsSglDetail retDetail) throws Exception {
        serviceId = "srv007_singleOuterTransfer";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter);
        if (!"".equals(bankFront.token)) {
            xmlWriter.writeElementString("functionId", "srv007");
            xmlWriter.writeElementString("functionName", "跨行汇款");
            xmlWriter.writeStartElement("opReq");
            xmlWriter.writeElementString("serialNo", p_req1908.singleDetail.askNumber);
            xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(new Date()));
            XElement tmpXElement = new XElement("ReqParam", "");
            tmpXElement.addChild(new XElement("FKZH", p_req1908.singleDetail.payAct));
            tmpXElement.addChild(new XElement("SKZH", p_req1908.singleDetail.recAct));
            tmpXElement.addChild(new XElement("SKHM", p_req1908.singleDetail.recName));
            tmpXElement.addChild(new XElement("SKYH", p_req1908.singleDetail.recBankLocation));
            tmpXElement.addChild(new XElement("SKSH", p_req1908.singleDetail.getOppProvinceAndCity()[0]));
            tmpXElement.addChild(new XElement("SKSI", p_req1908.singleDetail.getOppProvinceAndCity()[1]));
            tmpXElement.addChild(new XElement("JYJE", p_req1908.singleDetail.payAmount));
            tmpXElement.addChild(new XElement("BIZH", convertCurToBank(p_req1908.singleDetail.payCur)));
            tmpXElement.addChild(new XElement("ZZLX", "02"));//人行大额
            //0：普通1：加急
            if (!StringHelper.isNullOrEmpty(p_req1908.singleDetail.paySpd) && p_req1908.singleDetail.paySpd.equals("1")) {
                tmpXElement.addChild(new XElement("ZZLB", "1"));
            } else {
                tmpXElement.addChild(new XElement("ZZLB", "0"));
            }
            tmpXElement.addChild(new XElement("YOTU", p_req1908.singleDetail.purpose));
            tmpXElement.addChild(new XElement("SKHH", p_req1908.singleDetail.cnapsCode));//收款行号
            nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndElement();

            String signXml = getDataSignData(xmlWriter);//获取签名数据
            if (signnatrue(signXml) == true) {
                xmlWriter.writeElementString("signData", signature);//进行签名
                xmlWriter.writeEndDocument();//报文结束

                String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));//发送银行
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        retDetail.respCode = "0";
                        retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                        if (tmpBkReader.getFirstText("/NBCBEBankData/opRep") != null) {
                            retDetail.respInfo = tmpBkReader.getFirstText("/NBCBEBankData/opRep/opResult/SBYY");
                        ////交易应答+交易状态 0000+90 90：交易成功91：交易失败94：银行已受理99：系统处理中
                        retDetail.transState = tmpBkReader.getFirstText("/NBCBEBankData/opRep/opResult/YDDM") + "+" + tmpBkReader.getFirstText("/NBCBEBankData/opRep/opResult/JYZT");
                        } else {
                            retDetail.respInfo = tmpBkReader.getFirstText("/NBCBEBankData/errorMsg");
                            retDetail.transState = tmpBkReader.getFirstText("/NBCBEBankData/retCode");
                        }
                        retDetail.payInfoCode = retDetail.transState;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpSbMsg.toString();
                    }
                } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                    retDetail.respCode = "0";
                    retDetail.respInfo = tmpStrRet[1];
                    retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    retDetail.transState = PaymentState.FAIL_Payment;
                    retDetail.payInfoCode = tmpStrRet[0];
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpStrRet[1];
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSign[1];
            }
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = "登录失败";
        }
        return retDetail;
    }

    //1944 状态查询
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);

        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        serviceId = "srv008_transferResultInfoQuery";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        try {
            writeCommonHeader(xmlWriter);
            if (!"".equals(bankFront.token)) {
                xmlWriter.writeElementString("functionId", "srv008");
                xmlWriter.writeElementString("functionName", "转账结果查询");
                xmlWriter.writeStartElement("opReq");
                xmlWriter.writeElementString("serialNo", p_req1944.reqHeader.transSeqID);
                xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(new Date()));
                xmlWriter.writeStartElement("ReqParam");
                xmlWriter.writeElementString("JYXH", p_req1944.reqHeader.reqSeqID);
                xmlWriter.writeEndElement();
                xmlWriter.writeEndElement();
                String signXml = getDataSignData(xmlWriter);//获取签名数据
                if (signnatrue(signXml) == true) {
                    xmlWriter.writeElementString("signData", signature);//进行签名
                    xmlWriter.writeEndDocument();

                    String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String returnCode = tmpBkReader.getFirstText("/NBCBEBankData/retCode");
                            String returnMsg = tmpBkReader.getFirstText("/NBCBEBankData/errorMsg");
                            if (returnCode != null && isActiveRetCode(returnCode)) {
                                while (tmpBkReader.read("/NBCBEBankData/opRep/opResult")) {
                                    String info = tmpBkReader.readedXElement.getSingleText("YDDM");//应答
                                    //90：交易成功91：交易失败93：被银行取消94：银行已受理99：系统处理中
                                    String state = tmpBkReader.readedXElement.getSingleText("JYZT");//状态
                                    retDetail.respCode = "0";
                                    retDetail.respInfo = tmpBkReader.readedXElement.getSingleText("SBYY");
                                    retDetail.payInfoCode = info + "+" + state;
                                    retDetail.transState = info + "+" + state;
                                    retDetail.reqSeqID = p_req1944.askNumber;
                                }
                            } else {
                                retDetail.respCode = "0";
                                retDetail.respInfo = returnMsg;
                                retDetail.payInfoCode = returnCode;
                                retDetail.transState = returnCode;
                                retDetail.reqSeqID = p_req1944.askNumber;
                            }
                        } else {
                            retDetail.respCode = "-1";
                            retDetail.respInfo = tmpSbMsg.toString();
                        }
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpStrRet[1];
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSign[1];
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = "登录失败";
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }

        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
